package com.ssy.lingxi.search.serviceImpl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.ssy.lingxi.common.constant.CommonConstant;
import com.ssy.lingxi.common.constant.Constants;
import com.ssy.lingxi.common.constant.marketing.ActivityTypeEnum;
import com.ssy.lingxi.common.constant.tree.Node;
import com.ssy.lingxi.common.constant.tree.TreeUtils;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.component.redis.service.IRedisStringUtils;
import com.ssy.lingxi.marketing.api.feign.ActivityGoodsControllerFeign;
import com.ssy.lingxi.marketing.api.model.request.ProductTagReq;
import com.ssy.lingxi.marketing.api.model.response.ProductTagResp;
import com.ssy.lingxi.search.api.model.request.CustomerAttributeRequest;
import com.ssy.lingxi.search.api.model.request.CustomerAttributeValueRequest;
import com.ssy.lingxi.search.api.model.request.channel.ChannelCommoditySearchRequest;
import com.ssy.lingxi.search.api.model.response.*;
import com.ssy.lingxi.search.api.model.response.channel.ChannelCommodityDetailResponse;
import com.ssy.lingxi.search.api.model.response.channel.ChannelCommoditySearchResponse;
import com.ssy.lingxi.search.common.SortTypeEnum;
import com.ssy.lingxi.search.common.tree.CategoryNode;
import com.ssy.lingxi.search.entity.*;
import com.ssy.lingxi.search.entity.SimpleCustomerAttribute;
import com.ssy.lingxi.search.entity.SimpleCustomerAttributeValue;
import com.ssy.lingxi.search.entity.channel.ChannelCommodityMember;
import com.ssy.lingxi.search.entity.channel.ChannelUnitPricePic;
import com.ssy.lingxi.search.repository.CommodityRepository;
import com.ssy.lingxi.search.service.IChannelShopService;
import com.ssy.lingxi.search.service.ICommodityService;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.core.CountRequest;
import org.elasticsearch.client.core.CountResponse;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.script.Script;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.Max;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.ScriptSortBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * 店铺实现类
 * @author jw.chen
 * @version 2.0.0
 * @date 2020/6/22
 */
@Service
public class ChannelShopServiceImpl implements IChannelShopService {

    @Resource
    private ICommodityService commodityService;

    @Resource
    private RestHighLevelClient restHighLevelClient;

    @Resource
    private IRedisStringUtils redisStringUtils;

    @Resource
    private CommodityRepository commodityRepository;

    @Resource
    private ActivityGoodsControllerFeign activityGoodsControllerFeign;

    /**
     * 分页查询商品列表
     * @param channelCommoditySearchRequest
     * @return
     */
    @Override
    public PageData<ChannelCommoditySearchResponse> searchCommodityList(UserLoginCacheDTO sysUser, ChannelCommoditySearchRequest channelCommoditySearchRequest, Boolean isHighlight, Boolean isScoreShop){
        //获取参数
        Long shopId = channelCommoditySearchRequest.getShopId();
        Long channelMemberId = channelCommoditySearchRequest.getChannelMemberId();
        Long childChannelMemberId = channelCommoditySearchRequest.getChildChannelMemberId();
        Long childChannelMemberRoleId = channelCommoditySearchRequest.getChildChannelMemberRoleId();
        //查询商品信息
        PageData<Commodity> result = this.getCommodityList(channelCommoditySearchRequest, isHighlight);
        //根据条件过滤渠道商品
        List<ChannelCommoditySearchResponse> resultList = result.getData().stream().map(commodity -> {
            List<ChannelCommodityMember> memberList = commodity.getMemberList();
            if(memberList != null && memberList.size() > 0) {
                for (ChannelCommodityMember channelCommodityMember : memberList) {
                    Long channelCommodityMemberId = channelCommodityMember.getChannelMemberId();
                    Long childMemberId = channelCommodityMember.getMemberId();
                    Long childMemberRoleId = channelCommodityMember.getMemberRoleId();
                    List<ChannelUnitPricePic> unitPricePicList = channelCommodityMember.getUnitPricePicList();
                    if (channelCommodityMemberId.equals(channelMemberId) && childMemberRoleId.equals(childChannelMemberRoleId) && (childMemberId == 0 || childMemberId.equals(childChannelMemberId))) {
                        ChannelCommoditySearchResponse channelCommoditySearchResponse = BeanUtil.copyProperties(commodity, ChannelCommoditySearchResponse.class);
                        //不同商城显示不同的已售数量
                        List<CommoditySoldCount> commoditySoldCountList = channelCommodityMember.getCommoditySoldCountList();
                        if (commoditySoldCountList != null && commoditySoldCountList.size() > 0) {
                            commoditySoldCountList.forEach(commoditySoldCount -> {
                                Long commoditySoldCountShopId = commoditySoldCount.getShopId();
                                double sold = commoditySoldCount.getSold();
                                if (commoditySoldCountShopId.longValue() == shopId.longValue()) {
                                    channelCommoditySearchResponse.setSold(sold);
                                }
                            });
                        }
                        //设置渠道商品相关信息
                        channelCommoditySearchResponse.setChannelCommodityId(channelCommodityMember.getId());
                        channelCommoditySearchResponse.setMemberId(channelCommodityMember.getChannelMemberId());
                        channelCommoditySearchResponse.setMemberName(channelCommodityMember.getChannelMemberName());
                        channelCommoditySearchResponse.setMemberRoleId(channelCommodityMember.getChannelMemberRoleId());
                        channelCommoditySearchResponse.setCreditScore(channelCommodityMember.getCreditScore());

                        //计算最大值和最小值
                        List<Map<String, Double>> collect = unitPricePicList.stream().filter(unitPriceAndPic -> unitPriceAndPic != null && unitPriceAndPic.getUnitPrice() != null && unitPriceAndPic.getUnitPrice().size() > 0).map(ChannelUnitPricePic::getUnitPrice).collect(Collectors.toList());
                        if (!collect.isEmpty()) {
                            Double min = Collections.min(collect.stream().map(m -> Collections.min(m.values())).collect(Collectors.toList()));
                            Double max = Collections.max(collect.stream().map(m -> Collections.max(m.values())).collect(Collectors.toList()));
                            channelCommoditySearchResponse.setMin(min);
                            channelCommoditySearchResponse.setMax(max);
                        }

                        //积分商城显示库存
                        if (isScoreShop) {
                            ChannelCommodityDetailResponse commodityStock = this.getCommodityStock(shopId, commodity, channelMemberId, sysUser);
                            if (commodityStock != null) {
                                double stockCount = commodityStock.getUnitPricePicList().stream().mapToDouble(UnitPricePicResponse::getStockCount).sum();
                                channelCommoditySearchResponse.setStockCount(stockCount);
                            }
                        }
                        return channelCommoditySearchResponse;
                    }
                }
            }
            return null;
        }).filter(Objects::nonNull).collect(Collectors.toList());

        //积分商城不需要显示活动信息
        if(!isScoreShop){
            //获取商品相关的活动信息
            this.getActivityGoods(resultList, shopId, sysUser.getMemberId(), sysUser.getMemberRoleId());
        }

        return new PageData<>(result.getTotalCount(), resultList);
    }

    /**
     * 根据条件查询商品信息
     * @param channelCommoditySearchRequest     搜索条件
     * @param isHighlight   是否高亮显示
     */
    public PageData<Commodity> getCommodityList(ChannelCommoditySearchRequest channelCommoditySearchRequest, Boolean isHighlight){
        //获取参数
        int pageSize = channelCommoditySearchRequest.getPageSize();
        int current = channelCommoditySearchRequest.getCurrent();
        Integer orderType = channelCommoditySearchRequest.getOrderType();
        Long shopId = channelCommoditySearchRequest.getShopId();
        Long channelMemberId = channelCommoditySearchRequest.getChannelMemberId();
        Long childChannelMemberId = channelCommoditySearchRequest.getChildChannelMemberId();
        Long childChannelMemberRoleId = channelCommoditySearchRequest.getChildChannelMemberRoleId();

        //查询条件
        QueryBuilder query = this.getBoolQueryBuilder(channelCommoditySearchRequest);
        //根据条件获取排序规则
        SortBuilder scriptSortBuilder = getScriptSortBuilder(orderType, channelMemberId, childChannelMemberId, childChannelMemberRoleId, shopId);
        //查询商品
        return this.getHighlightList(query, current - 1, pageSize, scriptSortBuilder, isHighlight);
    }

    /**
     * 获取商品相关的活动信息
     * @param resultList
     * @param shopId
     * @param loginMemberId
     * @param loginMemberRoleId
     */
    private void getActivityGoods(List<ChannelCommoditySearchResponse> resultList, Long shopId, Long loginMemberId, Long loginMemberRoleId){
        //增加活动标签
        if (!CollectionUtils.isEmpty(resultList)) {
            // 活动内部接口请求
            ProductTagReq productTagReq = new ProductTagReq();
            productTagReq.setShopId(shopId);
            //判断是否已登录
            if(loginMemberId != null && loginMemberId > 0){
                productTagReq.setMemberId(loginMemberId);
                productTagReq.setRoleId(loginMemberRoleId);
            }

            //过滤不显示的活动类型
            List<Integer> filterActivityType = new ArrayList<>();
            filterActivityType.add(ActivityTypeEnum.GROUP_PURCHASE.getCode());
            productTagReq.setFilterActivityType(filterActivityType);

            Map<Long, ProductTagResp> productTagRespMap=new HashMap<>();
            List<Long> commodityList = resultList.stream().map(ChannelCommoditySearchResponse::getChannelCommodityId).collect(Collectors.toList());
            productTagReq.setProductIds(commodityList);
            try {
                //获取商品信息
                Wrapper<List<ProductTagResp>> listWrapper = activityGoodsControllerFeign.listActivityGoodsProductTag(productTagReq);
                if (listWrapper != null && listWrapper.getCode() == ResponseCode.SUCCESS.getCode()) {
                    List<ProductTagResp> productTagRespList = listWrapper.getData();
                    productTagRespMap = productTagRespList.stream().collect(Collectors.toMap(ProductTagResp::getProductId, ProductTagResp -> ProductTagResp));
                }
            }catch (Exception e){
                e.printStackTrace();
            }
            //设置活动信息
            for (ChannelCommoditySearchResponse response : resultList) {
                ProductTagResp productTagResp = productTagRespMap.get(response.getId());
                if (productTagResp!=null) {
                    response.setPreferentialPrice(productTagResp.getPreferentialPrice());
                    response.setTagList(productTagResp.getTagList());
                }
            }
        }
    }

    /**
     * 构建查询条件
     * @param searchRequest 参数
     * @return
     */
    private BoolQueryBuilder getBoolQueryBuilder(ChannelCommoditySearchRequest searchRequest){
        // 查询条件
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        // 获取查询条件
        Long memberId = searchRequest.getMemberId();
        Long memberRoleId = searchRequest.getMemberRoleId();
        String memberName = searchRequest.getMemberName();
        String name = searchRequest.getName();
        Long brandId = searchRequest.getBrandId();
        Long storeId = searchRequest.getStoreId();
        List<Long> storeIdList = searchRequest.getStoreIdList();
        String provinceCode = searchRequest.getProvinceCode();
        String cityCode = searchRequest.getCityCode();
        Long categoryId = searchRequest.getCategoryId();
        Long customerCategoryId = searchRequest.getCustomerCategoryId();
        List<CustomerAttributeRequest> customerAttributeList = searchRequest.getCustomerAttributeList();
        Double max = searchRequest.getMax();
        Double min = searchRequest.getMin();
        List<Integer> priceTypeList = searchRequest.getPriceTypeList();
        List<Long> idInList = searchRequest.getIdInList();
        List<Long> idNotInList = searchRequest.getIdNotInList();
        Long shopId = searchRequest.getShopId();
        Long channelMemberId = searchRequest.getChannelMemberId();
        Long channelMemberRoleId = searchRequest.getChannelMemberRoleId();
        Long childChannelMemberId = searchRequest.getChildChannelMemberId();
        Long childChannelMemberRoleId = searchRequest.getChildChannelMemberRoleId();

        // id搜索
        if(idInList != null && !idInList.isEmpty()){
            queryBuilder.must(QueryBuilders.termsQuery("id", idInList));
        }
        if(idNotInList != null && !idNotInList.isEmpty()){
            queryBuilder.mustNot(QueryBuilders.termsQuery("id", idNotInList));
        }

        // 拼接会员id搜索
        if(memberId != null && memberId > 0){
            queryBuilder.must(QueryBuilders.matchQuery("memberId", memberId));
        }
        if(memberRoleId != null && memberRoleId > 0){
            queryBuilder.must(QueryBuilders.matchQuery("memberRoleId", memberRoleId));
        }

        // 拼接店铺id搜索
        if(storeId != null && storeId > 0){
            queryBuilder.must(QueryBuilders.matchQuery("storeId", storeId));
        }
        if(storeIdList != null && !storeIdList.isEmpty()){
            queryBuilder.must(QueryBuilders.termsQuery("storeId", storeIdList));
        }

        // 拼接会员名称搜索
        if(StringUtils.isNotEmpty(memberName)){
            MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery(memberName, "memberName");
            queryBuilder.must(multiMatchQueryBuilder);
        }

        // 拼接关键字搜索(商品名称、标语、卖点)
        if(StringUtils.isNotEmpty(name)){
            MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery(name, "name", "slogan", "sellingPoint");
            queryBuilder.must(multiMatchQueryBuilder);
        }

        // 拼接品牌搜索
        if(brandId != null && brandId > 0){
            queryBuilder.must(QueryBuilders.matchQuery("brand.id", brandId));
        }

        // 拼接省份搜索
        if(StringUtils.isNotEmpty(provinceCode)){
            BoolQueryBuilder province = QueryBuilders.boolQuery().must(QueryBuilders.matchQuery("isAllArea", false)).must(QueryBuilders.matchQuery("commodityAreaList.provinceCode", provinceCode));
            queryBuilder.must(QueryBuilders.boolQuery().should(QueryBuilders.matchQuery("isAllArea", true)).should(province));
        }

        // 拼接城市搜索
        if(StringUtils.isNotEmpty(cityCode)){
            BoolQueryBuilder city = QueryBuilders.boolQuery().must(QueryBuilders.matchQuery("commodityAreaList.isAllCity", false)).must(QueryBuilders.matchQuery("commodityAreaList.cityCode", cityCode));
            queryBuilder.must(QueryBuilders.boolQuery().should(QueryBuilders.matchQuery("isAllArea", true)).should(QueryBuilders.matchQuery("commodityAreaList.isAllCity", true)).should(city));
        }

        // 拼接分类搜索
        String attributeKey = null;
        String attributeValueKey = null;
        if(categoryId != null && categoryId > 0){
            String categoryKey = "customerCategory.category.fullId:*";
            queryBuilder.must(QueryBuilders.queryStringQuery(categoryKey + String.format(Constants.CATEGORY_FULL_ID_NUM, categoryId) + "*"));
            // 拼接属性搜索
            attributeKey = "unitPricePicList.attributeAndValueList.customerAttribute.attribute.id";
            attributeValueKey = "unitPricePicList.attributeAndValueList.customerAttributeValue.attributeValue.id";
        }
        if(customerCategoryId != null && customerCategoryId > 0){
            String categoryKey = "customerCategory.fullId:*";
            queryBuilder.must(QueryBuilders.queryStringQuery(categoryKey + String.format(Constants.CATEGORY_FULL_ID_NUM, customerCategoryId) + "*"));
            // 拼接属性搜索
            attributeKey = "unitPricePicList.attributeAndValueList.customerAttribute.id";
            attributeValueKey = "unitPricePicList.attributeAndValueList.customerAttributeValue.id";
        }

        if(customerAttributeList != null && !customerAttributeList.isEmpty()){
            BoolQueryBuilder customerAttributeQueryBuilder = QueryBuilders.boolQuery();
            String finalAttributeKey = attributeKey;
            String finalAttributeValueKey = attributeValueKey;
            customerAttributeList.forEach(customerAttribute -> {
                Long customerAttributeId = customerAttribute.getCustomerAttributeId();
                List<CustomerAttributeValueRequest> customerAttributeValueList = customerAttribute.getCustomerAttributeValueList();
                customerAttributeValueList.forEach(customerAttributeValue -> {
                    Long customerAttributeValueId = customerAttributeValue.getId();
                    BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
                    boolQueryBuilder.must(QueryBuilders.termQuery(finalAttributeKey, customerAttributeId));
                    boolQueryBuilder.must(QueryBuilders.termQuery(finalAttributeValueKey, customerAttributeValueId));
                    customerAttributeQueryBuilder.should(boolQueryBuilder);
                });
            });
            queryBuilder.must(customerAttributeQueryBuilder);
        }

        // 拼接定价方式搜索
        if(priceTypeList != null && !priceTypeList.isEmpty()){
            queryBuilder.must(QueryBuilders.termsQuery("priceType", priceTypeList));
        }

        //供应商会员id
        if(channelMemberId != null && channelMemberId > 0){
            queryBuilder.must(QueryBuilders.matchQuery("memberList.channelMemberId", channelMemberId));
        }

        //供应商会员角色id
        if(channelMemberRoleId != null && channelMemberRoleId > 0){
            queryBuilder.must(QueryBuilders.matchQuery("memberList.channelMemberRoleId", channelMemberRoleId));
        }

        //采购商会员id
        if(childChannelMemberId != null && childChannelMemberId > 0){
//            BoolQueryBuilder must = QueryBuilders.boolQuery().must(QueryBuilders.matchQuery("memberList.memberId", 0)).must(QueryBuilders.matchQuery("memberList.memberRoleId", childChannelMemberRoleId));
//            queryBuilder.must(QueryBuilders.boolQuery().should(must).should(QueryBuilders.matchQuery("memberList.memberId", childChannelMemberId)));
//            BoolQueryBuilder must = QueryBuilders.boolQuery().must(QueryBuilders.matchQuery("memberList.memberRoleId", childChannelMemberRoleId));
            queryBuilder.must(QueryBuilders.boolQuery().should(QueryBuilders.matchQuery("memberList.memberId", childChannelMemberId)).should(QueryBuilders.matchQuery("memberList.memberId", 0)));
        }
        if(childChannelMemberRoleId != null && childChannelMemberRoleId > 0){
            queryBuilder.must(QueryBuilders.matchQuery("memberList.memberRoleId", childChannelMemberRoleId));
        }

        // 拼接价格搜索
        if(min != null && min > 0 && max != null && max > 0){
            queryBuilder.must(QueryBuilders.rangeQuery("memberList.min").gte(min).lte(max));
        }else{
            if(min != null && min > 0){
                queryBuilder.must(QueryBuilders.rangeQuery("memberList.min").gte(min));
            }
            if(max != null && max > 0){
                queryBuilder.must(QueryBuilders.rangeQuery("memberList.min").lte(max));
            }
        }

        if(shopId != null && shopId > 0){
            queryBuilder.must(QueryBuilders.matchQuery("memberList.shopList.shopId", shopId));
        }

        return queryBuilder;
    }

    /**
     * 根据排序类型获取对应的排序规则
     * @param orderType                         排序类型
     * @param channelMemberId                   渠道会员id
     * @param childChannelMemberId              下级渠道会员id
     * @param childChannelMemberRoleId          下级渠道会员角色id
     * @param shopId                            商城id
     */
    private SortBuilder getScriptSortBuilder(Integer orderType, Long channelMemberId, Long childChannelMemberId, Long childChannelMemberRoleId, Long shopId) {
        if (orderType != null && orderType > 0) {
            if (orderType.equals(SortTypeEnum.PriceDown.getCode())) {
                return this.getChannelMemberPriceScriptQuery(channelMemberId, childChannelMemberId, childChannelMemberRoleId);
            } else if (orderType.equals(SortTypeEnum.PriceUp.getCode())) {
                return this.getChannelMemberPriceScriptQuery(channelMemberId, childChannelMemberId, childChannelMemberRoleId);
            } else if (orderType.equals(SortTypeEnum.SoldDown.getCode())) {
                return this.getCommoditySoldScriptSortBuilder(shopId).order(SortOrder.DESC);
            } else if (orderType.equals(SortTypeEnum.CreditDown.getCode())) {
                return SortBuilders.fieldSort("creditScore").order(SortOrder.DESC);
            }
        }
        // 默认按上架时间倒序
        return this.getCommodityPublishTimeScriptQuery(channelMemberId);
    }

    /**
     * 通过上架时间计算权重查询
     */
    private ScriptSortBuilder getCommodityPublishTimeScriptQuery(Long channelMemberId){
        String inlineScript = "def memberList = params._source.memberList;" +
                "       double score = 0;" +
                "       if(memberList != null){" +
                "           for (int i = 0; i < memberList.length; i++) {" +
                "               def channelMemberId = memberList[i].channelMemberId;" +
                "               def publishTime = memberList[i].publishTime;" +
                "               if(channelMemberId == " + channelMemberId + "){" +
                "                   score = publishTime;" +
                "               }" +
                "           }" +
                "       }" +
                "       return score;";
        return SortBuilders.scriptSort(new Script(inlineScript), ScriptSortBuilder.ScriptSortType.NUMBER);
    }

    /**
     * 通过渠道会员不同价格计算权重查询
     */
    private ScriptSortBuilder getChannelMemberPriceScriptQuery(Long channelMemberId, Long childChannelMemberId, Long childChannelMemberRoleId){
        String inlineScript = "def channelMember = params._source.memberList;" +
                "  double score = 0;" +
                "  for (int i = 0; i < channelMember.length; i++) {" +
                "     if(channelMember[i].channelMemberId == " + channelMemberId + " && channelMember[i].memberRoleId == " + childChannelMemberRoleId + "){" +
                "          if(channelMember[i].memberId == 0 || channelMember[i].memberId == " + childChannelMemberId + "){" +
                "              score = channelMember[i].min;" +
                "          }" +
                "     }" +
                "  }" +
                "  return score;";
        return SortBuilders.scriptSort(new Script(inlineScript), ScriptSortBuilder.ScriptSortType.NUMBER);
    }

    /**
     * 通过已售数量计算权重排序
     */
    private ScriptSortBuilder getCommoditySoldScriptSortBuilder(Long shopId){
        String inlineScript = "def commoditySoldCountList = params._source.commoditySoldCountList;" +
                "       double score = 0;" +
                "       if(commoditySoldCountList != null){" +
                "           for (int i = 0; i < commoditySoldCountList.length; i++) {" +
                "               def commoditySoldCountShopId = commoditySoldCountList[i].shopId;" +
                "               def commoditySoldCountSold= commoditySoldCountList[i].sold;" +
                "               if(commoditySoldCountShopId == " + shopId + "){" +
                "                   score = commoditySoldCountSold;" +
                "               }" +
                "           }" +
                "       }" +
                "       return score;";
        return SortBuilders.scriptSort(new Script(inlineScript), ScriptSortBuilder.ScriptSortType.NUMBER);
    }

    /**
     * 高亮显示关键字
     * @param query
     * @param current
     * @param pageSize
     * @return
     */
    private PageData<Commodity> getHighlightList(QueryBuilder query, int current, int pageSize, SortBuilder sortBuilder, Boolean isHighlight){
        PageData<Commodity> commodity = new PageData<>();
        try{
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder().trackTotalHits(true);
            sourceBuilder.query(query);
            // 获取记录数，默认10
            sourceBuilder.from(current * pageSize);
            sourceBuilder.size(pageSize);
            //排序
            sourceBuilder.sort(sortBuilder);

            //是否需要高亮
            if(isHighlight){
                HighlightBuilder highlightBuilder = new HighlightBuilder();
                HighlightBuilder.Field highlightTitle = new HighlightBuilder.Field("name");  //为name字段创建字段高光色。
                highlightBuilder.field(highlightTitle);
                highlightBuilder.preTags("<span class='highlight'>");
                highlightBuilder.postTags("</span>");
                sourceBuilder.highlighter(highlightBuilder);
            }

            SearchRequest searchRequest = new SearchRequest(Constants.ES_COMMODITY_INDEX);
            searchRequest.source(sourceBuilder);
            SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

            //是否需要高亮
            if(isHighlight){
                //遍历结果
                for(SearchHit hit : response.getHits()){
                    Map<String, Object> source = hit.getSourceAsMap();
                    //处理高亮片段
                    Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                    HighlightField nameField = highlightFields.get("name");
                    if(nameField!=null){
                        Text[] fragments = nameField.fragments();
                        StringBuilder nameTmp = new StringBuilder();
                        for(Text text:fragments){
                            nameTmp.append(text);
                        }
                        //将高亮片段组装到结果中去
                        source.put("name", nameTmp.toString());
                    }
                }
            }

            long total = response.getHits().getTotalHits().value;
            SearchHits hits = response.getHits();
            SearchHit[] searchHits = hits.getHits();
            List<Commodity> commodityList = Arrays.stream(searchHits).map(searchHit -> new JSONObject(searchHit.getSourceAsMap()).toBean(Commodity.class)).collect(Collectors.toList());
            commodity.setTotalCount(total);
            commodity.setData(commodityList);
        }catch (Exception e){
            e.printStackTrace();
        }
        return commodity;
    }

    /**
     * 查询商品分类树
     * @return
     */
    @Override
    public List<Node> getCategoryTree(Long channelMemberId, Long shopId) {
        // 查询条件
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();

        // 按商城环境
        if(shopId != null && shopId > 0){
            queryBuilder.must(QueryBuilders.matchQuery("memberList.shopList.shopId", shopId));
        }

        //供应商
        if(channelMemberId != null && channelMemberId > 0){
            queryBuilder.must(QueryBuilders.matchQuery("memberList.channelMemberId", channelMemberId));
        }

        //构建查询条件
        SearchRequest search = new SearchRequest(Constants.ES_COMMODITY_INDEX);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.size(0);
        searchSourceBuilder.query(queryBuilder);
        //分组
        TermsAggregationBuilder aggregationCategoryId = AggregationBuilders.terms("group_categoryId").field("customerCategory.fullId.keyword").size(1200000);
        searchSourceBuilder.aggregation(aggregationCategoryId);
        search.source(searchSourceBuilder);
        try{
            CategoryNode categoryNode = new CategoryNode();
            //搜索
            SearchResponse searchResponse = restHighLevelClient.search(search, RequestOptions.DEFAULT);
            Aggregations aggregations = searchResponse.getAggregations();
            if(aggregations != null){
                Terms brandTerms = aggregations.get("group_categoryId");
                List<? extends Terms.Bucket> brandBuckets = brandTerms.getBuckets();
                if(brandBuckets != null){
                    brandBuckets.forEach(bucket -> {
                        //将品类进行组装
                        String fullId = String.valueOf(bucket.getKey());
                        if(fullId.contains(Constants.SPLIT_STR_FULL_ID)){
                            String[] split = fullId.split(Constants.TRANSFER_STR + Constants.SPLIT_STR_FULL_ID);
                            if(split.length > 0){
                                for(int i = 0; i < split.length; i++){
                                    if(i == 0){
                                        //一级品类
                                        Set<Long> rootList = categoryNode.getRootList() == null ? new HashSet<>() : categoryNode.getRootList();
                                        rootList.add(Long.valueOf(split[i]));
                                        categoryNode.setRootList(rootList);
                                    }
                                    //所有品类
                                    Set<Long> sourceList = categoryNode.getSourceList() == null ? new HashSet<>() : categoryNode.getSourceList();
                                    sourceList.add(Long.valueOf(split[i]));
                                    categoryNode.setSourceList(sourceList);

                                }
                            }
                        }else{
                            //商品挂在一级品类下
                            Set<Long> rootList = categoryNode.getRootList() == null ? new HashSet<>() : categoryNode.getRootList();
                            rootList.add(Long.valueOf(fullId));
                            categoryNode.setRootList(rootList);
                            //所有品类
                            Set<Long> sourceList = categoryNode.getSourceList() == null ? new HashSet<>() : categoryNode.getSourceList();
                            sourceList.add(Long.valueOf(fullId));
                            categoryNode.setSourceList(sourceList);
                        }
                    });
                }
            }
            Map<String, String> categoryMap = redisStringUtils.hGetAll(Constants.REDIS_KEY_CUSTOMER_CATEGORY, Constants.REDIS_PRODUCT_INDEX);
            Set<Long> rootCategoryIdList = categoryNode.getRootList();
            Set<Long> sourceCategoryIdList = categoryNode.getSourceList();
            //组装树结构
            if(rootCategoryIdList != null && !rootCategoryIdList.isEmpty()){
                List<Node> rootList = TreeUtils.getNodeList(rootCategoryIdList, categoryMap);
                List<Node> sourceList = TreeUtils.getNodeList(sourceCategoryIdList, categoryMap);
                return TreeUtils.buildTree(sourceList, rootList);
            }
            return new ArrayList<>();
        }catch (Exception e){
            e.printStackTrace();
            return new ArrayList<>();
        }
    }

    /**
     * 查询商品属性
     * @return
     */
    @Override
    public List<AttributeResponse> getAttributeByCategoryId(Long shopId, Long channelMemberId, Long categoryId) {
        HashMap<Long, AttributeResponse> attributeMap = new HashMap<>();
        try{
            // 查询条件
            BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
            // 按商城环境
            if(shopId != null && shopId > 0){
                queryBuilder.must(QueryBuilders.matchQuery("memberList.shopList.shopId", shopId));
            }
            //供应商
            if(channelMemberId != null && channelMemberId > 0){
                queryBuilder.must(QueryBuilders.matchQuery("memberList.channelMemberId", channelMemberId));
            }
            // 按品类
            if(categoryId != null && categoryId > 0){
                queryBuilder.must(QueryBuilders.matchQuery("customerCategory.id", categoryId));
            }
            //查询
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder().trackTotalHits(true);
            sourceBuilder.query(queryBuilder);
            // 通过CountRequest查询获得count
            CountRequest countRequest = new CountRequest();
            countRequest.indices(Constants.ES_COMMODITY_INDEX);
            CountResponse countResponse = restHighLevelClient.count(countRequest, RequestOptions.DEFAULT);
            sourceBuilder.size(Long.valueOf(countResponse.getCount()).intValue());

            SearchRequest searchRequest = new SearchRequest(Constants.ES_COMMODITY_INDEX);
            searchRequest.source(sourceBuilder);
            SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            SearchHits hits = response.getHits();
            SearchHit[] searchHits = hits.getHits();
            List<Commodity> commodityList = Arrays.stream(searchHits).map(searchHit -> new JSONObject(searchHit.getSourceAsMap()).toBean(Commodity.class)).collect(Collectors.toList());

            Map<String, String> attributeSortMap = redisStringUtils.hGetAll(Constants.REDIS_KEY_CUSTOMER_CATEGORY_ATTRIBUTE_SORT + categoryId, Constants.REDIS_PRODUCT_INDEX);

            commodityList.forEach(commodity -> commodity.getCommodityAttributeList().forEach(commodityAttribute -> {
                SimpleCustomerAttribute customerAttribute = commodityAttribute.getCustomerAttribute();
                if(customerAttribute != null){
                    Long attributeId = customerAttribute.getId();
                    String attributeName = customerAttribute.getName();
                    Boolean isSearch = customerAttribute.getIsSearch();
                    if(isSearch){
                        List<SimpleCustomerAttributeValue> customerAttributeValueSet = commodityAttribute.getCustomerAttributeValueList();
                        customerAttributeValueSet.forEach(customerAttributeValue -> {
                            AttributeValueResponse attributeValueResponse = new AttributeValueResponse();
                            attributeValueResponse.setId(customerAttributeValue.getId());
                            attributeValueResponse.setValue(customerAttributeValue.getValue());

                            AttributeResponse attributeResponse = attributeMap.get(attributeId);
                            if(attributeResponse != null){
                                List<AttributeValueResponse> attributeValueList = attributeResponse.getAttributeValueList();
                                if(attributeValueList != null){
                                    if(!attributeValueList.contains(attributeValueResponse)){
                                        attributeValueList.add(attributeValueResponse);
                                    }
                                }else{
                                    attributeValueList = new ArrayList<>();
                                    attributeValueList.add(attributeValueResponse);
                                }
                            }else{
                                attributeResponse = new AttributeResponse();
                                attributeResponse.setId(attributeId);
                                attributeResponse.setName(attributeName);

                                List<AttributeValueResponse> attributeValueList = new ArrayList<>();
                                attributeValueList.add(attributeValueResponse);
                                attributeResponse.setAttributeValueList(attributeValueList);
                            }

                            String sort = attributeSortMap.get(String.valueOf(attributeId));
                            if (StringUtils.isNotBlank(sort)){
                                attributeResponse.setSort(Integer.valueOf(sort));
                            }else {
                                attributeResponse.setSort(0);
                            }

                            attributeMap.put(attributeId, attributeResponse);
                        });
                    }
                }
            }));
        }catch (Exception e){
            e.printStackTrace();
        }
        List<AttributeResponse> attributeResponses = new ArrayList<>(attributeMap.values());
        //属性排序
        attributeResponses = attributeResponses.stream().sorted(Comparator.comparingInt(AttributeResponse::getSort)).collect(Collectors.toList());

        return attributeResponses;
    }

    /**
     * 查询商品品牌
     * @return
     */
    @Override
    public List<BrandResponse> getBrand(Long channelMemberId, Long shopId, Long customerCategoryId) {
        List<BrandResponse> brandList = new ArrayList<>();
        // 查询条件
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();

        // 按商城环境
        if(shopId != null && shopId > 0){
            queryBuilder.must(QueryBuilders.matchQuery("memberList.shopList.shopId", shopId));
        }

        //品类
        if(customerCategoryId != null && customerCategoryId > 0){
            String categoryKey = "customerCategory.fullId:*";
            queryBuilder.must(QueryBuilders.queryStringQuery(categoryKey + String.format(Constants.CATEGORY_FULL_ID_NUM, customerCategoryId) + "*"));
        }

        //供应商
        if(channelMemberId != null && channelMemberId > 0){
            queryBuilder.must(QueryBuilders.matchQuery("memberList.channelMemberId", channelMemberId));
        }

        //构建查询条件
        SearchRequest search = new SearchRequest(Constants.ES_COMMODITY_INDEX);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.size(0);
        searchSourceBuilder.query(queryBuilder);
        //分组
        TermsAggregationBuilder aggregationBrandId = AggregationBuilders.terms("group_brandId").field("brand.id").size(1200000)
                .subAggregation(AggregationBuilders.terms("group_brandName").field("brand.name.keyword").subAggregation(AggregationBuilders.terms("group_brandLogoUrl").field("brand.logoUrl.keyword")));
        searchSourceBuilder.aggregation(aggregationBrandId);
        search.source(searchSourceBuilder);
        //搜索
        try{
            SearchResponse searchResponse = restHighLevelClient.search(search, RequestOptions.DEFAULT);
            Aggregations aggregations = searchResponse.getAggregations();
            if(aggregations != null){
                Terms brandTerms = aggregations.get("group_brandId");
                List<? extends Terms.Bucket> brandBuckets = brandTerms.getBuckets();
                if(brandBuckets != null){
                    brandBuckets.forEach(bucket -> {
                        Terms brandNameTerms = bucket.getAggregations().get("group_brandName");
                        List<? extends Terms.Bucket> brandNameBuckets = brandNameTerms.getBuckets();
                        if(brandNameBuckets != null){
                            brandNameBuckets.forEach(bucketName -> {
                                Terms brandLogoUrlTerms = bucketName.getAggregations().get("group_brandLogoUrl");
                                List<? extends Terms.Bucket> brandLogoUrlBuckets = brandLogoUrlTerms.getBuckets();
                                brandLogoUrlBuckets.forEach(bucketLogoUrl -> {
                                    BrandResponse brand = new BrandResponse();
                                    brand.setId(Long.valueOf(String.valueOf(bucket.getKey())));
                                    brand.setName(String.valueOf(bucketName.getKey()));
                                    brand.setLogoUrl(String.valueOf(bucketLogoUrl.getKey()));
                                    brandList.add(brand);
                                });
                            });
                        }
                    });
                }
            }
            return brandList;
        }catch (Exception e){
            return new ArrayList<>();
        }
    }

    /**
     * 查询归属地市
     * @return
     */
    @Override
    public List<ProvinceResponse> getArea(Long shopId, Long channelMemberId) {
        // 查询条件
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        // 拼接会员搜索
        if(channelMemberId != null && channelMemberId > 0){
            queryBuilder.must(QueryBuilders.matchQuery("memberList.channelMemberId", channelMemberId));
        }
        // 按商城环境
        if(shopId != null && shopId > 0){
            queryBuilder.must(QueryBuilders.matchQuery("memberList.shopList.shopId", shopId));
        }
        return commodityService.queryEsArea(queryBuilder);
    }

    /**
     * 查询渠道商品最大价格/最大积分
     * @return
     */
    @Override
    public Double getCommodityMaxPrice(Long channelMemberId) {
        //分组
        AggregationBuilder builder = AggregationBuilders.max("maxPrice").field("memberList.max");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.aggregation(builder);
        //指定查找内容
        SearchRequest search = new SearchRequest(Constants.ES_COMMODITY_INDEX);
        if(channelMemberId != null && channelMemberId > 0){
            //构建查询条件
            BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
            // 拼接会员搜索
            queryBuilder.must(QueryBuilders.matchQuery("memberList.channelMemberId", channelMemberId));
            searchSourceBuilder.query(queryBuilder);
        }
        search.source(searchSourceBuilder);

        try{
            SearchResponse searchResponse = restHighLevelClient.search(search, RequestOptions.DEFAULT);
            Aggregations aggregations = searchResponse.getAggregations();
            Max maxPrice = aggregations.get("maxPrice");
            if(maxPrice != null && !maxPrice.getValueAsString().equals("-Infinity")){
                return Math.ceil(maxPrice.getValue());
            }else{
                return 0D;
            }
        }catch (Exception e){
            return 0D;
        }
    }

    /**
     * 查询商品详情
     * @param commodityId
     * @param channelMemberId
     * @param sysUser
     * @return
     */
    @Override
    public ChannelCommodityDetailResponse getCommodityDetail(Long shopId, Long commodityId, Long channelMemberId, UserLoginCacheDTO sysUser) {
        Commodity commodity = commodityRepository.findById(commodityId).orElse(null);
        if(commodity != null){
            ChannelCommodityDetailResponse channelCommodityResponse = this.getCommodityStock(shopId, commodity, channelMemberId, sysUser);
            //判断是否上架
            List<ChannelCommodityMember> memberList = commodity.getMemberList();
            memberList.forEach(channelCommodityMember -> {
                Long memberId = channelCommodityMember.getMemberId();
                Long memberRoleId = channelCommodityMember.getMemberRoleId();
                if(memberId == 0 || (memberId.equals(sysUser.getMemberId()) && memberRoleId.equals(sysUser.getMemberRoleId()))){
                    List<CommodityShop> commodityShopList = channelCommodityMember.getShopList();
                    List<Long> commodityShopIdList = commodityShopList.stream().map(CommodityShop::getShopId).collect(Collectors.toList());
                    if(commodityShopIdList.size() > 0 && commodityShopIdList.contains(shopId)){
                        channelCommodityResponse.setIsPublish(true);
                    }
                }
            });
            return channelCommodityResponse;
        }else{
            throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_NOT_EXIST);
        }
    }

    /**
     * 通过商品skuId查询商品详情
     * @param commoditySkuId
     * @param channelMemberId
     * @param sysUser
     * @return
     */
    @Override
    public ChannelCommodityDetailResponse getCommodityDetailBySkuId(Long shopId, Long commoditySkuId, Long channelMemberId, UserLoginCacheDTO sysUser) {
        Commodity commodity = commodityRepository.findByMemberListUnitPricePicListId(commoditySkuId);
        if(commodity != null){
            ChannelCommodityDetailResponse channelCommodityResponse = this.getCommodityStock(shopId, commodity, channelMemberId, sysUser);
            //判断是否上架
            List<ChannelCommodityMember> memberList = commodity.getMemberList();
            memberList.forEach(channelCommodityMember -> {
                Long memberId = channelCommodityMember.getMemberId();
                Long memberRoleId = channelCommodityMember.getMemberRoleId();
                if(memberId == 0 || (memberId.equals(sysUser.getMemberId()) && memberRoleId.equals(sysUser.getMemberRoleId()))){
                    List<CommodityShop> commodityShopList = channelCommodityMember.getShopList();
                    List<Long> commodityShopIdList = commodityShopList.stream().map(CommodityShop::getShopId).collect(Collectors.toList());
                    if(commodityShopIdList.size() > 0 && commodityShopIdList.contains(shopId)){
                        channelCommodityResponse.setIsPublish(true);
                    }
                }
            });
            return channelCommodityResponse;
        }else{
            throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_NOT_EXIST);
        }
    }

    /**
     * 查询商品库存
     * @param commodity
     * @param channelMemberId
     */
    @Override
    public ChannelCommodityDetailResponse getCommodityStock(Long shopId, Commodity commodity, Long channelMemberId, UserLoginCacheDTO sysUser) {
        Long loginMemberId = sysUser.getMemberId();
        Long loginMemberRoleId = sysUser.getMemberRoleId();
        List<Long> upperChannelMemberIds = sysUser.getUpperChannelMemberIds();
        if(commodity != null){
            ChannelCommodityDetailResponse channelCommodityResponse = new ChannelCommodityDetailResponse();
            BeanUtil.copyProperties(commodity, channelCommodityResponse);
            List<ChannelCommodityMember> memberList = commodity.getMemberList();
            if(memberList != null && !memberList.isEmpty()){
                //用于判断是否有该渠道商品的权限
                AtomicReference<Boolean> flag = new AtomicReference<>(false);
                memberList.forEach(channelCommodityMember -> {
                    Long commodityChannelMemberId = channelCommodityMember.getChannelMemberId();
                    Long commodityMemberId = channelCommodityMember.getMemberId();
                    Long commodityMemberRoleId = channelCommodityMember.getMemberRoleId();
                    List<ChannelUnitPricePic> unitPriceAndPicList = new ArrayList<>(channelCommodityMember.getUnitPricePicList());
                    if(!unitPriceAndPicList.isEmpty()) {
                        //只取该渠道的商品信息
                        if(commodityChannelMemberId.equals(channelMemberId)){
                            List<Long> shopList = channelCommodityMember.getShopList().stream().map(CommodityShop::getShopId).collect(Collectors.toList());
                            if(shopList.size() > 0){
                                if(shopList.contains(shopId)){
                                    //查看自己发布的商品
                                    if (loginMemberId.equals(channelMemberId)) {
                                        List<UnitPricePicResponse> unitPricePicResponseList = unitPriceAndPicList.stream().map(unitPriceAndPic -> {
                                            Long commodityUnitPriceAndPicId = unitPriceAndPic.getCommodityUnitPriceAndPicId();
                                            String redisKey = CommonConstant.FREIGHT_SPACE_REDIS_KEY + shopId + "_" + commodityUnitPriceAndPicId;
                                            Map<String, String> map = redisStringUtils.hGetAll(redisKey, Constants.REDIS_PRODUCT_INDEX);
                                            Double stockCount = map.values().stream().mapToDouble(Double::parseDouble).sum();
                                            unitPriceAndPic.setStockCount(stockCount);
                                            UnitPricePicResponse unitPricePicResponse = new UnitPricePicResponse();
                                            BeanUtil.copyProperties(unitPriceAndPic, unitPricePicResponse);
                                            //加载商品的图片
                                            commodity.getUnitPricePicList().forEach(unitPricePic -> {
                                                if(unitPricePic.getId().longValue() == commodityUnitPriceAndPicId.longValue()){
                                                    unitPricePicResponse.setCommodityPic(unitPricePic.getCommodityPic());
                                                }
                                            });
                                            return unitPricePicResponse;
                                        }).collect(Collectors.toList());
                                        channelCommodityResponse.setUnitPricePicList(unitPricePicResponseList);
                                        //取最大值和最小值
                                        channelCommodityResponse.setMin(channelCommodityMember.getMin());
                                        channelCommodityResponse.setMax(channelCommodityMember.getMax());
                                        channelCommodityResponse.setMemberId(channelCommodityMember.getChannelMemberId());
                                        channelCommodityResponse.setMemberName(channelCommodityMember.getChannelMemberName());
                                        channelCommodityResponse.setMemberRoleId(channelCommodityMember.getChannelMemberRoleId());
                                        channelCommodityResponse.setMemberRoleName(channelCommodityMember.getChannelMemberRoleName());
                                        channelCommodityResponse.setLogistics(BeanUtil.copyProperties(channelCommodityMember.getLogistics(), LogisticsResponse.class));
                                        channelCommodityResponse.setStoreId(channelCommodityMember.getStoreId());
                                        channelCommodityResponse.setIsMemberPrice(channelCommodityMember.getIsMemberPrice());
                                        channelCommodityResponse.setTaxRate(channelCommodityMember.getTaxRate());
                                        channelCommodityResponse.setId(channelCommodityMember.getId());
                                        channelCommodityResponse.setCommodityId(commodity.getId());
                                        flag.set(true);
                                    } else {
                                        if(commodityMemberRoleId.equals(loginMemberRoleId)){
                                            //发布给所有渠道
                                            if (commodityMemberId == 0) {
                                                //判断该商品是否是他的上级发布的
                                                if(upperChannelMemberIds.contains(commodityChannelMemberId)){
                                                    channelCommodityResponse.setUnitPricePicList(this.getUnitPricePicResponse(commodity, unitPriceAndPicList, loginMemberId, shopId));
                                                    //取最大值和最小值
                                                    channelCommodityResponse.setMin(channelCommodityMember.getMin());
                                                    channelCommodityResponse.setMax(channelCommodityMember.getMax());
                                                    channelCommodityResponse.setMemberId(channelCommodityMember.getChannelMemberId());
                                                    channelCommodityResponse.setMemberName(channelCommodityMember.getChannelMemberName());
                                                    channelCommodityResponse.setMemberRoleId(channelCommodityMember.getChannelMemberRoleId());
                                                    channelCommodityResponse.setMemberRoleName(channelCommodityMember.getChannelMemberRoleName());
                                                    channelCommodityResponse.setLogistics(BeanUtil.copyProperties(channelCommodityMember.getLogistics(), LogisticsResponse.class));
                                                    channelCommodityResponse.setStoreId(channelCommodityMember.getStoreId());
                                                    channelCommodityResponse.setIsMemberPrice(channelCommodityMember.getIsMemberPrice());
                                                    channelCommodityResponse.setTaxRate(channelCommodityMember.getTaxRate());
                                                    channelCommodityResponse.setId(channelCommodityMember.getId());
                                                    channelCommodityResponse.setCommodityId(commodity.getId());
                                                    flag.set(true);
                                                }
                                            } else if(commodityMemberId.equals(loginMemberId)){
                                                //发布给某个会员
                                                channelCommodityResponse.setUnitPricePicList(this.getUnitPricePicResponse(commodity, unitPriceAndPicList, loginMemberId, shopId));
                                                //取最大值和最小值
                                                channelCommodityResponse.setMin(channelCommodityMember.getMin());
                                                channelCommodityResponse.setMax(channelCommodityMember.getMax());
                                                channelCommodityResponse.setMemberId(channelCommodityMember.getChannelMemberId());
                                                channelCommodityResponse.setMemberName(channelCommodityMember.getChannelMemberName());
                                                channelCommodityResponse.setMemberRoleId(channelCommodityMember.getChannelMemberRoleId());
                                                channelCommodityResponse.setMemberRoleName(channelCommodityMember.getChannelMemberRoleName());
                                                channelCommodityResponse.setLogistics(BeanUtil.copyProperties(channelCommodityMember.getLogistics(), LogisticsResponse.class));
                                                channelCommodityResponse.setStoreId(channelCommodityMember.getStoreId());
                                                channelCommodityResponse.setIsMemberPrice(channelCommodityMember.getIsMemberPrice());
                                                channelCommodityResponse.setTaxRate(channelCommodityMember.getTaxRate());
                                                channelCommodityResponse.setId(channelCommodityMember.getId());
                                                channelCommodityResponse.setCommodityId(commodity.getId());
                                                flag.set(true);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                });
                if(flag.get()){
                    return channelCommodityResponse;
                }
            }
        }
        throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_NOT_EXIST);
    }

    /**
     * 获取库存信息
     * @param unitPriceAndPicList
     * @param memberId
     * @return
     */
    private List<UnitPricePicResponse> getUnitPricePicResponse(Commodity commodity, List<ChannelUnitPricePic> unitPriceAndPicList, Long memberId, Long shopId){
        List<UnitPricePicResponse> unitPricePicResponseList = new ArrayList<>();
        //组装redis键值格式
        List<HashMap<String, String[]>> keyFieldList = unitPriceAndPicList.stream().map(unitPriceAndPic -> {
            HashMap<String, String[]> map = new HashMap<>();
            String unitPriceAndPicId = CommonConstant.FREIGHT_SPACE_REDIS_KEY + shopId + "_" + unitPriceAndPic.getCommodityUnitPriceAndPicId();
            map.put(unitPriceAndPicId, new String[]{String.valueOf(memberId), CommonConstant.FREIGHT_All});
            return map;
        }).collect(Collectors.toList());

        //获取库存数据并赋值
        List<Object> resultList = redisStringUtils.hMGetBatch(keyFieldList, Constants.REDIS_PRODUCT_INDEX);
        for (int i = 0; i < unitPriceAndPicList.size(); i++) {
            ChannelUnitPricePic unitPriceAndPic = unitPriceAndPicList.get(i);
            //计算当前商品的库存数
            List<String> stockList = (List<String>) resultList.get(i);
            if (stockList != null && !stockList.isEmpty()) {
                List<String> collect = stockList.stream().filter(StrUtil::isNotEmpty).collect(Collectors.toList());
                if (!collect.isEmpty()) {
                    Double stockCount = collect.stream().map(Double::parseDouble).reduce(Double::sum).get();
                    unitPriceAndPic.setStockCount(stockCount);
                }
            }
            UnitPricePicResponse unitPricePicResponse = new UnitPricePicResponse();
            BeanUtil.copyProperties(unitPriceAndPic, unitPricePicResponse);
            unitPricePicResponseList.add(unitPricePicResponse);
            //加载商品的图片
            commodity.getUnitPricePicList().forEach(unitPricePic -> {
                if(unitPricePic.getId().longValue() == unitPriceAndPic.getCommodityUnitPriceAndPicId().longValue()){
                    unitPricePicResponse.setCommodityPic(unitPricePic.getCommodityPic());
                }
            });
        }
        return unitPricePicResponseList;
    }
}